import fetch from './fetch'
import store from '../store'
import { reduce } from '../utils/helper'
import API from './api_doc'
import G from '../global'
// import { URL } from './config'
const URL ='http://192.168.1.31/gongzhuyangzhi_backend/'
const NO_AUTH_CODE = [3000, 3001, 3002]

// 将 common 模块复制进 doctor、patient 中
function mergeAPI(api) {
  const common = api.common
  const nsArray = ['platform', 'user', 'common']
  return nsArray.reduce(
    (obj, k) => ({ ...obj, [k]: { ...api[k], ...common } }),
    {}
  )
}

// 移除空值字段
function removeEmptyField(obj) {
  return Object.keys(obj).reduce((o, k) => {
    const v = obj[k]
    if (
      v === 'undefined' ||
      typeof v === 'undefined' ||
      v === null
    ) {
      return o
    }
    return { ...o, [k]: v }
  }, {})
}

function generateAPI(api) {
  async function apiFunc(
    ns,
    value,
    options = {},
    { showError = true, showLoading = false, loadingText = '加载中' } = {}
  ) {
    const token = store.state.token
    const { m, path, params } = value
    const url = `${URL}${path}`
    const query = {
      method: m,
      data: removeEmptyField({ ...params, ...options, token }),
      headers: { 'App-Type': 2 }
    }

    try {
      if (showLoading) {
        G.showLoading({ title: loadingText, mask: true })
      }
      // console.log(query)
      const result = await fetch(url, query)
      return result
    } catch (e) {
      // code 错误使用原命名空间对应的 code，跳转需要使用实际token对应的跳转地址
      if (NO_AUTH_CODE.some(t => t === e.code)) {
        if (realNs) store.commit('emptyState')
        G.reLaunch({ url: '/pages/login' })
      }
      if (showError) {
        G.showToast({
          title: e.message || e.errMsg || '',
          icon: 'none',
          duration: 3000
        })
      }
      throw e
    } finally {
      if (showLoading) {
        G.hideLoading()
      }
    }
  }

  return reduce(api, (k, v) =>
    reduce(
      v,
      (_, value) =>
        function apiFuncFake(...rest) {
          return apiFunc(k, value, ...rest)
        }
    )
  )
}

export default generateAPI(mergeAPI(API))
